package com.qfedu.aunt.commons.job;

import com.qfedu.aunt.commons.constance.RedisConstance;
import com.qfedu.aunt.commons.manager.RedisManager;
import com.qfedu.aunt.commons.utils.ThreadPoolUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;
import sun.nio.ch.ThreadPool;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author xiaobobo
 * @title: ClearExpireReqJob
 * @projectName aunt_commons_2209
 * @description: 这个就是咋们的定时任务
 * @date 2022/11/15  14:10
 */
@Component
@Slf4j
public class ClearExpireReqJob {

    @Autowired
    private RedisManager redisManager;
    /**
     * 这个表示的是 每隔5秒钟执行一次我们的定时任务
      */
    @Scheduled(cron = "* 0/30 * * * ?")
    public void clear(){
        Executors.newSingleThreadExecutor().execute(new Runnable() {
            @Override
            public void run() {
                System.out.println("定时任务执行了....");
                //首先找到请求过我们的这个系统的IP地址
                Set set = redisManager.getSet(RedisConstance.getIP());
                //接下来遍历这个集合 组合我们新的key判断这个key是否满足条件
                Iterator it = set.iterator();
                while (it.hasNext()){
                    String ipAddress = (String) it.next();
                    log.info("找到的ip地址是:{}",ipAddress);
                    //接下来组合新的key
                    //找到限流的这个key
                    String limitKey=RedisConstance.getLIMIT()+ipAddress;
                    //需要找到限流中一天之前的数据
                    long dayAgo=System.currentTimeMillis()-1000*3600*24;
                    //接下来就要找到以前之前的数据(通过得分区间获取我们的数据 0-dayAgo )
                    Set setKey = redisManager.rangByScore(limitKey, 0, dayAgo);
                    //接下来再去删除过期数据
                    List<String> keys=new ArrayList<>();
                    Iterator iterator = setKey.iterator();
                    while (iterator.hasNext()){
                        String key = (String) iterator.next();
                        keys.add(key);
                        log.info("删除的这个key是:{}",key);
                    }
                    log.info("开始删除我们的过期数据了:"+keys);
                    redisManager.deleteZSet(limitKey,keys);
                }
            }
        });


    }


}
